<?php

/**
 * Author: LCY<409028735@qq.com>
 * Time: 2021/11/19 14:42
 * Note:
 */

namespace app\admin\model;

use think\Model;
use think\Db;
use util\Tree;

class AuthGroup extends Model
{

    /**
     * 获取所有正常的权限组
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 21:13
     * Note:
     */
    public static function getAllNormalGroups()
    {
        return self::where('status', 1)->order(['id' => 'asc'])->field('id,pid,title,status')->select();
    }

    /**
     * 获取所有正常的权限组
     * @return mixed
     * Author: LCY<409028735@qq.com>
     * Time: 2021/12/25 21:13
     * Note:
     */
    public static function getAllNormalGroupsByPid($pid = 0)
    {
        return self::where('status', 1)->where('pid',$pid)->order(['id' => 'asc'])->field('id,pid,title,status')->select();
    }

    /**
     * 获取所有正常的权限组（tree的方式返回）
     *
     * @return void
     */
    public static function getAllNormalGroupsTree()
    {
        $datas = self::getAllNormalGroups();
        return Tree::dataToList($datas);
    }

    /**
     * 根据用户组获取可用的权限列表
     *
     * @param int $group_id 用户组id
     * @param int $checked_rules 已选中的ids
     * @return array
     */
    public static function getAuthListByGroupId($group_id, $checked_rules = [])
    {
        $group = self::get($group_id);
        $auths = [];
        if ($group->rules == '') {
            return $auths;
        } elseif ($group->rules == '*') {
            //查询全部的权限列表
            $auths = Db::name('auth_rule')->where('status', 1)->order(['sort' => 'asc', 'id' => 'asc'])->select();
        } else {
            //查询指定的权限列表
            $auths = Db::name('auth_rule')->where('status', 1)->where('id', 'in', $group->rules)->order(['sort' => 'asc', 'id' => 'asc'])->select();
        }

        return Tree::dataToTreeForJstree($auths,$checked_rules);
    }
}
